import shutil
import subprocess
import time
import requests

from playwright.sync_api import sync_playwright


class PlaywrightMCP:
    def __init__(self, host="localhost", port=7979):
        self.base_url = f"http://{host}:{port}"

    def get_browser_endpoint(self, browser_type="chromium"):
        """获取浏览器实例的 WebSocket 端点"""
        response = requests.post(
            f"{self.base_url}/{browser_type}/launch",
            json={"headless": False}
        )
        return response.json()["wsEndpoint"]

    def run_test_with_mcp(self):
        """使用 MCP 运行测试"""
        with sync_playwright() as pw:
            # 连接到 MCP 服务
            browser = pw.chromium.connect_over_cdp(
                f"http://localhost:{self.mcp_port}/chromium"
            )

            page = browser.new_page()
            page.goto("https://example.com")

            # 示例操作
            page.fill("#search", "Playwright MCP")
            page.click("#submit")

            # 截图保存
            page.screenshot(path="example.png")
            browser.close()
